//
//  BzrwbVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/8.
//

import UIKit

class BzrwbVC: BaseVC {
    
    var tableView: UITableView!

    var dataArray: [[String: Any]] = []
    var pageNum: Int = 1
    var pageSize: Int = 10
    var keyWord: String = ""
    var status: String = ""
    
    var sx_state: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadData))
        tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        NotificationCenter.default.addObserver(self, selector: #selector(BzrwbVC.loadData), name: NSNotification.Name(rawValue: "ReloadBzrwbVC"), object: nil)
        loadData()
    }
    
    // 数据刷新
    @objc func loadData() {
        pageNum = 1
        dataArray.removeAll()
        loadMoreData()
    }
    @objc func loadMoreData() {
        let paramet: [String: String] = [
            "beginStatus": "30",
            "keyWord": keyWord,
            "status": status,
            "pageNo" : pageNum.description,
            "pageSize" : pageSize.description
        ]
        EWERequest.lgf("label", paramet, .get) { [weak self] (data) in
            let result = (data["result"] as? [[String: Any]]) ?? []
            if result.count > 0 {
                self?.dataArray += result
                self?.pageNum += 1
            }
            self?.tableView.reloadData()
            self?.endRefreshing()
            if result.count == 0 {
                self?.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }
        } _: { [weak self] (error) in
            SVProgressHUD.showError(error)
            self?.endRefreshing()
        }
    }
    func endRefreshing() {
        self.tableView.mj_header?.endRefreshing()
        self.tableView.mj_footer?.endRefreshing()
    }
    
    // 派包
    override func rightBtnSelect(_ sender: UIButton) {
        let actionSheet = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        actionSheet.addAction(UIAlertAction.init(title: "取消", style: .cancel) { (action) in
            
        })
        actionSheet.addAction(UIAlertAction.init(title: "手动派包", style: .default) { (action) in
            let vc = YbxqVC()
            vc.type = "标注样本"
            self.navigationController?.show(vc, sender: self)
        })
        actionSheet.addAction(UIAlertAction.init(title: "自动派包", style: .default) { (action) in
            let vc = ZdbzpbVC()
            self.navigationController?.show(vc, sender: self)
        })
        present(actionSheet, animated: true, completion: nil)
    }

    // 删除
    func deleteCell(_ indexPath: IndexPath) {
        let id = (dataArray[indexPath.item]["id"] as? String) ?? ""
        let paramet: [String: String] = [
            "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
        ]
        EWERequest.lgf("label/" + id, paramet, .delete) { [weak self] (data) in
            self?.dataArray.remove(at: indexPath.item)
            self?.tableView.reloadData()
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    @objc func s_sx() {
        SxV().showIn(self.view, ["状态"], ["状态": ["标注开始", "标注完成", "标注包超时"]], [self.sx_state]) { [weak self] (sxv, name, state) in
            if state.first == 0 {
                self?.status = ""
            } else if state.first == 1 {
                self?.status = "10"
            } else if state.first == 2 {
                self?.status = "20"
            } else if state.first == 2 {
                self?.status = "30"
            }
            if self?.sx_state != state.first {
                self?.loadData()
            }
            self?.sx_state = state.first ?? 0
        }
    }
}

extension BzrwbVC: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        keyWord = textField.text ?? ""
        loadData()
    }
}

extension BzrwbVC: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        let status = (dataArray[indexPath.item]["status"] as? Int) ?? 10
        if status == 20 {
            return UITableViewCell.EditingStyle.none
        } else {
            return UITableViewCell.EditingStyle.delete
        }
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            deleteCell(indexPath)
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell: BzrwbCell = tableView.dequeueReusableCell(withIdentifier: "BzrwbCell", for: indexPath) as! BzrwbCell
        let status = (dataArray[indexPath.item]["status"] as? Int) ?? 10
        // 10:标注开始；20：标注完成;30:标注超时
        if status == 10 {
            cell.status.text = "标注开始"
            cell.status.backgroundColor = UIColor.init(lgf_HexString: "F27C0F")?.withAlphaComponent(0.1)
            cell.status.textColor = UIColor.init(lgf_HexString: "F27C0F")
            cell.status.layer.borderColor = UIColor.init(lgf_HexString: "F27C0F")?.withAlphaComponent(0.2).cgColor
        } else if status == 20 {
            cell.status.text = "标注完成"
            cell.status.backgroundColor = UIColor.init(lgf_HexString: "0F88F2")?.withAlphaComponent(0.1)
            cell.status.textColor = UIColor.init(lgf_HexString: "0F88F2")
            cell.status.layer.borderColor = UIColor.init(lgf_HexString: "0F88F2")?.withAlphaComponent(0.2).cgColor
        } else if status == 30 {
            cell.status.text = "标注包超时"
            cell.status.backgroundColor = UIColor.init(lgf_HexString: "DE6161")?.withAlphaComponent(0.1)
            cell.status.textColor = UIColor.init(lgf_HexString: "DE6161")
            cell.status.layer.borderColor = UIColor.init(lgf_HexString: "DE6161")?.withAlphaComponent(0.2).cgColor
        }
        // 1609924219000  1610529019000
        cell.tzzx.text = (dataArray[indexPath.item]["name"] as? String) ?? ""
        cell.sj.text = ((dataArray[indexPath.item]["createdTime"] as? Int) ?? 0).description.lgf_TimeStampToDate().lgf_TimeStr("yyyy.MM.dd") + "-" + ((dataArray[indexPath.item]["expiryTime"] as? Int) ?? 0).description.lgf_TimeStampToDate().lgf_TimeStr("yyyy.MM.dd")
        cell.wj.text = (dataArray[indexPath.item]["sampleTotal"] as? Int)?.description ?? ""
        cell.yh.text = (dataArray[indexPath.item]["markEmpTotal"] as? Int)?.description ?? ""
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = YblbVC()
        vc.type = "标注"
        vc.id = (dataArray[indexPath.item]["id"] as? String) ?? ""
        self.navigationController?.show(vc, sender: self)
    }
    
}
